package com.naml.e_syn;

/**
 * @author marin
 * @version 1.0
 * @date 2025/4/26 17:24
 * @desc 使用实现Runnable接口实现窗口卖票--实现线程同步---synchronized（同步方法的方式）
 */
@SuppressWarnings("all")
public class ThreadSynSellTicket02 {
    public static void main(String[] args) {
        ThreadSynSellTicket0 sellTicket02 = new ThreadSynSellTicket0();
        Thread thread1 = new Thread(sellTicket02);
        Thread thread2 = new Thread(sellTicket02);
        Thread thread3 = new Thread(sellTicket02);
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

@SuppressWarnings("all")
class ThreadSynSellTicket0 implements Runnable {
    //由于实现方式，只会创建一个对象，所以不需要static修饰
    private int count = 100;
    private boolean loop = true;

    public synchronized void sellTicket() {
        if (count <= 0) {
            loop = false;
            System.err.println("售票结束...");
            return;
        }
        try {
            Thread.sleep(50);
            System.out.println("窗口"+Thread.currentThread().getName() +"：卖票，剩余张数："+(--count));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void run() {
        while(loop){
           sellTicket();
        }
    }
}
